package com.tanhua.dubbo.api.mongo;

import com.tanhua.domain.mongo.Friend;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.dubbo.api.FriendApi;
import org.apache.dubbo.config.annotation.Service;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;

import java.util.List;

/**
 * @Classname FriendApiImpl
 * @Description TODO
 * @Date 2021/3/16 16:11
 * @Created by gan
 */
@Service
public class FriendApiImpl implements FriendApi {

    @Autowired
    private MongoTemplate mongoTemplate;



    //添加好友
    @Override
    public void add(Long userId, Long friendId) {

        //记录好友关系
        //1，查询好友关系是否存在
        Query query=new Query(
                Criteria.where("userId").is(userId)
                .and("friendId").is(friendId)
        );
        if(!mongoTemplate.exists(query, Friend.class)){
            //2,保存好友关系
            Friend friend=new Friend();
            friend.setFriendId(friendId);
            friend.setUserId(userId);
            friend.setId(ObjectId.get());
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }
        query = new Query(
                Criteria.where("userId").is(friendId)
                        .and("friendId").is(userId)
        );
        if(!mongoTemplate.exists(query, Friend.class)) {
            //2、保存好友关系   userId-friendId
            Friend friend = new Friend();
            friend.setUserId(friendId);
            friend.setFriendId(userId);
            friend.setId(ObjectId.get());
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }

    }


    //分页查询好友
    @Override
    public PageResult findPage(Long userId, Integer page, Integer size, String keyword) {
        //构建查询条件
        Query query =new Query();
        query.addCriteria(Criteria.where("userId").is(userId));
        long count = mongoTemplate.count(query, Friend.class);
        //构造分页结果
        PageResult<Friend>pageResult=new PageResult<>();
        pageResult.setPage((long)page);
        pageResult.setPagesize((long)size);
        pageResult.setCounts(count);
        query.with(PageRequest.of(page-1,size));
        //查询
        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        pageResult.setItems(friends);
        return pageResult;
    }
}
